Python argparse接收参数使用

必选参数

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
# -*- coding:utf-8 -*-
import argparse
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument('integer', type=int, help='display an integer')
args = parser.parse_args()
print args
print args.integer

# 调用及输出:
(public) D:\dev\project\test\mongo>python arg_test.py 3
Namespace(integer=3)
3

(public) D:\dev\project\test\mongo>python arg_test.py
usage: arg_test.py [-h] integer
arg_test.py: error: too few arguments

(public) D:\dev\project\test\mongo>python arg_test.py "1"
Namespace(integer=1)
1

可选参数

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
# -*- coding:utf-8 -*-
import argparse

if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument("--arg1", help="arg1 number", type=int)
parser.add_argument("--arg2", help="arg2 number", type=int)

args = parser.parse_args()
if args.arg1:
print u"参数1", args.arg1

if args.arg2:
print u"参数2", args.arg2

# 调用及输出:
(public) D:\dev\project\test\mongo>python arg_test.py --arg1 1
参数1 1

(public) D:\dev\project\test\mongo>python arg_test.py --arg2 2
参数2 2

(public) D:\dev\project\test\mongo>python arg_test.py --arg1 1 --arg2 2
参数1 1
参数2 2

(public) D:\dev\project\test\mongo>python arg_test.py 1
usage: arg_test.py [-h] [--arg1 ARG1] [--arg2 ARG2]
arg_test.py: error: unrecognized arguments: 1

(public) D:\dev\project\test\mongo>python arg_test.py